package com.hhhn.wk.main.tab3.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.main.tab2.entity.Commodity;
import com.hhhn.wk.main.tab4.address.AddressAllActivity;
import com.hhhn.wk.main.tab4.address.entity.Address;
import com.hhhn.wk.pay.PayActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.mi.AES;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.customview.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/3/25 0025    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 确认订单--商品详情
 * * * * * * * * * * * */
public class ConfirmOrderActivity extends BaseActivity {
    DecimalFormat df   = new DecimalFormat("######0.00");
    private BaseActivity activity;
    private TextView tv_title;

    private String shipAddressId="";//收货地址id
    private TextView tv_addressName;//收货姓名
    private TextView tv_addressPhone;//收货手机号
    private TextView tv_address;//收货地址
    private LinearLayout ll_Address_p;//收货地址有
    private LinearLayout ll_Address_n;//收货地址无
    public static ArrayList<Address> mArrayListAddress=new ArrayList<Address>();
    int type=0;//跳转类型
    ArrayList<String> cartIdList =new ArrayList<>();
//    /*商品列表*/
//    private ArrayList<Commodity> commodityList =new ArrayList<>();//商品数组
//    private MyAdaper<Commodity> mAdapter;
//    private MyListView mLoadListView;
    private TextView tv_goPay;//下单


    private TextView tv_goodsMoney;//商品金额
    private TextView tv_goodsfreight;//运费
    private TextView tv_total;//下单-总价格
    private ImageView iv_CommodityImg;//商品
    private TextView iv_CommodityName;//商品名称
    private TextView tv_priceNew;//商品价格
    private TextView tv_priceNumber;//商品数量



    private String tmpTotal="";//商品金额（不含运费）
    private String tmpFreight="";//商品总的运费
    private String total="";//订单总价格
    private String commodityImg="";//
    private String commodityName="";//

    private String priceNumber="";//
    private String goods_id="";//



    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mArrayListAddress.size() == 0) {
                        ll_Address_n.setVisibility(View.VISIBLE);
                        ll_Address_p.setVisibility(View.GONE);
                    } else {
                        ll_Address_n.setVisibility(View.GONE);
                        ll_Address_p.setVisibility(View.VISIBLE);
                        loadAddrssData();
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };
    //加载地址
    private void loadAddrssData() {
        shipAddressId=mArrayListAddress.get(0).getId();
        tv_addressName.setText(mArrayListAddress.get(0).getName());
        tv_addressPhone.setText(mArrayListAddress.get(0).getPhone());
        tv_address.setText(mArrayListAddress.get(0).getProvince()+mArrayListAddress.get(0).getCity()+mArrayListAddress.get(0).getTown()+mArrayListAddress.get(0).getAddress());

    }


    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_confirm_order2);
        activity=this;

        Intent intent=getIntent();
        goods_id=  intent.getStringExtra("goods_id");//商品ID
        commodityImg=  intent.getStringExtra("commodityImg");//图片
        commodityName=  intent.getStringExtra("commodityName");//名称
        tmpFreight=  intent.getStringExtra("tmpFreight");//运费
        tmpTotal=  intent.getStringExtra("zuizhongPrice");//最终单价格
        priceNumber=  intent.getStringExtra("number");//数量
        total=  intent.getStringExtra("zongji");//总计

    }
    @Override
    protected void initData() {
          tv_goodsMoney.setText("￥"+AllPublic.priceGSH(total));//商品金额

            if (!tmpFreight.equals("")&&!tmpFreight.equals("0")){


                double v = Double.parseDouble(tmpFreight) + Double.parseDouble(total);
                tv_total.setText("￥"+df.format(v)+"");//下单-总价格
                tv_goodsfreight.setText("￥"+AllPublic.priceGSH(tmpFreight));//运费
            }else {
                tv_total.setText("￥"+AllPublic.priceGSH(total));//下单-总价格
                tv_goodsfreight.setText("包邮");//运费
            }
        Glide.with(this).load(Constants.HTTPIMG+commodityImg).into(iv_CommodityImg);
          iv_CommodityName.setText(commodityName);//商品名称
          tv_priceNew.setText("￥"+AllPublic.priceGSH(tmpTotal));//一条商品价格
          tv_priceNumber.setText("X"+priceNumber);//商品数量
        getJSON();

    }

    @Override
    protected void initView() {
        tv_priceNumber=findViewById(R.id.tv_priceNumber);
        tv_priceNew=findViewById(R.id.tv_priceNew);
        iv_CommodityName=findViewById(R.id.iv_CommodityName);
        iv_CommodityImg=findViewById(R.id.iv_CommodityImg);
        tv_total=findViewById(R.id.tv_total);
        tv_title=findViewById(R.id.tv_title);
        tv_title.setText("确认订单");
        tv_addressName=findViewById(R.id.tv_addressName);
        tv_addressPhone=findViewById(R.id.tv_addressPhone);
        tv_address=findViewById(R.id.tv_address);
        ll_Address_p=findViewById(R.id.ll_Address_p);
        ll_Address_n=findViewById(R.id.ll_Address_n);

        tv_goodsMoney=findViewById(R.id.tv_goodsMoney);
        tv_goodsfreight=findViewById(R.id.tv_goodsfreight);
        tv_goPay=findViewById(R.id.tv_goPay);
    }

    @Override
    protected void initClick() {
        ll_Address_n.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(activity,AddressAllActivity.class);
                intent.putExtra("type",1);
                startActivityForResult(intent,1);
            }
        });
//        ll_Address_p.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent=new Intent(activity,AddressAllActivity.class);
//                intent.putExtra("type",1);
//                startActivityForResult(intent,1);
//            }
//        });
        tv_goPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    getXiadan();

            }
        });
    }
    //查询收货地址
    public void getJSON() {
        showLoad();
        RequestParams params = AllPublic.getParams(activity, "/showShipAddress", true);
        params.addParameter("cmUserId",getUser().getUid());/*用户Id*/
        Log.d("查询收货地址", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("查询收货地址：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Address myOrder=null;

                        for (int i=0;i<records.length();i++){
                            myOrder=new Address();
                            JSONObject object = records.getJSONObject(i);
                            String addressId = object.has("id") ? object.getString("id") : "";//id
                            String province = object.has("province") ? object.getString("province") : "";
                            String city = object.has("city") ? object.getString("city") : "";
                            String town = object.has("town") ? object.getString("town") : "";
                            String address = object.has("address") ? object.getString("address") : "";
                            String userName = object.has("shipName") ? object.getString("shipName") : "";//
                            String phone = object.has("shipTel") ? object.getString("shipTel") : "";//
                            int isShow = object.has("isDefault") ? object.getInt("isDefault") : 100902;//100901默认   100902不是默认
//                            if (isShow==100901){
                                myOrder.setProvince(province);
                                myOrder.setTown(town);
                                myOrder.setCity(city);
                                myOrder.setDef(isShow);
                                myOrder.setId(addressId);
                                myOrder.setAddress(address);
                                myOrder.setName(userName);
                                myOrder.setPhone(phone);
                                mArrayListAddress.add(myOrder);
//                            }

                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==1){
            String name = data.getStringExtra("name");
            String phone = data.getStringExtra("phone");
            String address = data.getStringExtra("address");
            shipAddressId = data.getStringExtra("shipAddressId");

            tv_addressName.setText(name);
            tv_addressPhone.setText(phone);
            tv_address.setText(address);
            ll_Address_n.setVisibility(View.GONE);
            ll_Address_p.setVisibility(View.VISIBLE);
        }
    }



    //下单--详情--
    public void getXiadan() {
        showLoad();
        RequestParams  params = AllPublic.getParamsProductOrder(activity, "/saveProductOrder", false);


//        params.addParameter("cmUserId",activity.getUser().getUid());
//        params.addParameter("shipAddressId",shipAddressId);//收货地址ID
//        params.addParameter("productId",goods_id);//商品id
//        params.addParameter("productNum",priceNumber);//商品数量
//        params.addParameter("price",tmpTotal);//商品价格
//        params.addParameter("freight",tmpFreight);//商品运费


        try {
            JSONObject person=new JSONObject();
            person.put("cmUserId",activity.getUser().getUid());
            person.put("shipAddressId",shipAddressId);//收货地址ID
            person.put("productId",goods_id);//商品id
            person.put("productNum",priceNumber);//商品数量
            person.put("price",tmpTotal);//商品价格
            person.put("freight",tmpFreight);//商品运费
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);//解密
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        String orderCode = data.has("orderCode") ? data.getString("orderCode") : "";//订单id
                        String orderId = data.has("id") ? data.getString("id") : "";//订单id
                        String money = data.has("money") ? data.getString("money") : "";//需支付
                        String deductibleAmount = data.has("deductibleAmount") ? data.getString("deductibleAmount") : "";//抵扣金额
                        String actualPayment = data.has("actualPayment") ? data.getString("actualPayment") : "";//实际

                        Intent intent=new Intent(activity, PayActivity.class);
                        intent.putExtra("orderId",orderId);
                        intent.putExtra("orderCode",orderCode);
                        intent.putExtra("money",money);
                        intent.putExtra("deductibleAmount",deductibleAmount);
                        intent.putExtra("shiji",actualPayment);
                        startActivity(intent);
                        finish();
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {

                dismissLoad();
            }
            @Override
            public void onFinished() {

                dismissLoad();
            }
        });
    }






}
